package cn.edu.hznu.util.io;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ChannelExample {
	
	private final static String FILE_PATH = "/Users/LVZY/Documents/Temp/Node-loaction.txt";
	private final static String FROM_PATH = "/Users/LVZY/Documents/Temp/from.txt";
	private final static String TO_PATH = "/Users/LVZY/Documents/Temp/to.txt";
	
	
	public static void bufferTest () {
		try (RandomAccessFile file = new RandomAccessFile(FILE_PATH, "rw")) {
			FileChannel channel = file.getChannel();
			ByteBuffer buf = ByteBuffer.allocate(48);
			int byteRead;
			while ((byteRead = channel.read(buf)) != -1) {
				System.out.println("Read " + byteRead);
				buf.flip();
				while (buf.hasRemaining()) {
					System.out.print((char)buf.get());
				}
				buf.clear();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void transferFromTest() {
		try (RandomAccessFile fromFile = new RandomAccessFile(FROM_PATH, "rw");
				RandomAccessFile toFile = new RandomAccessFile(TO_PATH, "rw")) {
			FileChannel fromChannel = fromFile.getChannel();
			FileChannel toChannel = toFile.getChannel();
			toChannel.transferFrom(fromChannel, 0L, fromChannel.size());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void transferToTest() {
		try (RandomAccessFile toFile = new RandomAccessFile(TO_PATH, "rw");
				RandomAccessFile fromFile = new RandomAccessFile(FROM_PATH, "rw")) {
			FileChannel toChannel = toFile.getChannel();
			FileChannel fromChannel = fromFile.getChannel();
			fromChannel.transferTo(0L, fromChannel.size(), toChannel);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
